package com.pocketmenu.persistence;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.pocketmenu.business.Constants;

import android.R.integer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract.Columns;
import android.util.Log;

public class ItemDataSource {
	
	// Database fields
	  private SQLiteDatabase database;	  
	  private int i=0;
	  private ItemDataSource h = this;
	  private SQLiteHelper dbHelper;
	  private String[] allColumns = 
		  { SQLiteHelper.COLUMN_ID,
			SQLiteHelper.COLUMN_ITEM_NAME,
			SQLiteHelper.COLUMN_ITEM_DESCRIPTION,			
			SQLiteHelper.COLUMN_ITEM_PRICE,
			SQLiteHelper.COLUMN_ITEM_ID_CATEGORY,
			SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT,
			SQLiteHelper.COLUMN_ITEM_RECOMENDED};

	  private SoapPrimitive resultado;
	  private boolean waitingForThread = true;
	  private boolean success = true;
	  
	  public ItemDataSource(Context context) {
	    dbHelper = new SQLiteHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();	    
	  }

	  public void close() {
	    dbHelper.close();
	  }

	  public Item create(String name, String description, int price, int idCategory, int idRestaurant, boolean recomended) {
	    ContentValues values = new ContentValues();
	    values.put(SQLiteHelper.COLUMN_ITEM_NAME, name);
	    values.put(SQLiteHelper.COLUMN_ITEM_DESCRIPTION, description);
	    values.put(SQLiteHelper.COLUMN_ITEM_PRICE, price);
	    values.put(SQLiteHelper.COLUMN_ITEM_ID_CATEGORY, idCategory);
	    values.put(SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT, idRestaurant);
	    values.put(SQLiteHelper.COLUMN_ITEM_RECOMENDED, recomended);
	    
	    long insertId = database.insert(SQLiteHelper.TABLE_ITEM, null,
	        values);
	    
	    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM,
	        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
	        null, null, null);
	    cursor.moveToFirst();
	    Item newTemp = cursorToObject(cursor);
	    cursor.close();
	    return newTemp;
	  }	  
	  
	  public Item create(String name, String description, int price, int idCategory, int idRestaurant, int[] ingredientId, boolean recomended) {
		    ContentValues values = new ContentValues();
		    values.put(SQLiteHelper.COLUMN_ITEM_NAME, name);
		    values.put(SQLiteHelper.COLUMN_ITEM_DESCRIPTION, description);
		    values.put(SQLiteHelper.COLUMN_ITEM_PRICE, price);
		    values.put(SQLiteHelper.COLUMN_ITEM_ID_CATEGORY, idCategory);
		    values.put(SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT, idRestaurant);
		    values.put(SQLiteHelper.COLUMN_ITEM_RECOMENDED, recomended);
		    
		    long insertId = database.insert(SQLiteHelper.TABLE_ITEM, null,
		        values);
		    
		    ContentValues valuesItemIngredient = new ContentValues();
		    for (int i : ingredientId) {
				valuesItemIngredient.put(SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_INGREDIENT, insertId);
				valuesItemIngredient.put(SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_ITEM, i);
				database.insert(SQLiteHelper.TABLE_ITEM_INGREDIENT, null, valuesItemIngredient);
				valuesItemIngredient.clear();
			}
		    
		    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM,
		        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
		        null, null, null);
		    cursor.moveToFirst();
		    Item newTemp = cursorToObject(cursor);
		    cursor.close();
		    return newTemp;
		  }
	  public void delete(Item toDelete) {
	    int id = toDelete.getId();
	    System.out.println("Item deleted with id: " + id);
	    database.delete(SQLiteHelper.TABLE_ITEM, SQLiteHelper.COLUMN_ID
	        + " = " + id, null);
	  }

	  public List<Item> getAll() {
	    List<Item> listTemp = new ArrayList<Item>();

	    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Item temp = cursorToObject(cursor);
	      listTemp.add(temp);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return listTemp;
	  }

	  public static Item cursorToObject(Cursor cursor) {
	    Item temp = new Item();
	    temp.setId(cursor.getInt(0));
	    temp.setName(cursor.getString(1));
	    temp.setDescription(cursor.getString(2));
	    temp.setPrice(cursor.getInt(3));
	    temp.setIdCategory(cursor.getInt(4));
	    temp.setIdRestaurant(cursor.getInt(5));
	    boolean rec = cursor.getInt(6) != 0;
	    temp.setRecomended(rec);
	    return temp;
	  }
	  
	  public Item getItem(int id)
	  {
		  String query = "select * from Item where " + SQLiteHelper.COLUMN_ID + " = " + id;
		  return cursorToObject(database.rawQuery(query, null));
	  }
	  
	  public Cursor getAll(int idRestaurant) {
		  		  
		  String whereClause = SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT + "=" + idRestaurant;
		    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM,
		        allColumns, whereClause, null, null, null, null);
		    
		    return cursor;
		  }
	  
	  public Cursor getAllByPrefences(int idRestaurant, boolean include)
	  {
		  int intInclude = include ? 1 : 0;
		  String query = "select i." + SQLiteHelper.COLUMN_ID + ", i."+ SQLiteHelper.COLUMN_ITEM_NAME + ", i." + SQLiteHelper.COLUMN_ITEM_DESCRIPTION + ", i." + SQLiteHelper.COLUMN_ITEM_PRICE + ", i." + SQLiteHelper.COLUMN_ITEM_ID_CATEGORY + ", i." + SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT + " from " + SQLiteHelper.TABLE_ITEM + " i join " + SQLiteHelper.TABLE_ITEM_INGREDIENT 
				  + " ii on i._id = ii." + SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_ITEM 
				  + " join " + SQLiteHelper.TABLE_PREFERENCE + " p on ii." + SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_INGREDIENT + " = p." + SQLiteHelper.COLUMN_PREFERENCE_ID_INGREDIENT
				  + " where p." + SQLiteHelper.COLUMN_PREFERENCE_INCLUDE + " = " + intInclude;
		  
		  return database.rawQuery(query, null);				  
	  }
	  
	  public Cursor getItems(int idRestaurant, boolean includeIngredients, int idCategory)
	  {
		  int intInclude = includeIngredients ? 1 : 0;
		  
		  String query = 
				  "select item." + SQLiteHelper.COLUMN_ID 
				  + ", item."+ SQLiteHelper.COLUMN_ITEM_NAME 
				  + ", item." + SQLiteHelper.COLUMN_ITEM_DESCRIPTION 
				  + ", item." + SQLiteHelper.COLUMN_ITEM_PRICE 
				  + ", item." + SQLiteHelper.COLUMN_ITEM_ID_CATEGORY 
				  + ", item." + SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT
				  + ", item." + SQLiteHelper.COLUMN_ITEM_RECOMENDED
				  + " from " + SQLiteHelper.TABLE_ITEM + " item" 				  
				  + " where item." + SQLiteHelper.COLUMN_ITEM_ID_RESTAURANT + " = " + idRestaurant 
				  + " and item." + SQLiteHelper.COLUMN_ITEM_ID_CATEGORY + " = " + idCategory;
		  
		  return database.rawQuery(query, null);				  
	  }	  
	  
	  public boolean loadFromWeb(){
		  Thread networkThread = new Thread() {
      	    @Override
      	    public void run() {
	      	      
	  	    	//request       	    
	      	    String metodo = "select";	
	      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
	      	    request.addProperty("tabla", "Item");
	
	      	    //modelo sobre
	      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
	      	    sobre.dotNet = true;
	
	      	    sobre.setOutputSoapObject(request);
	
	      	    //transporte
	      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
	      	    transporte.debug = true;           
	
	      	    //llamada
	      	    try {
	      	    	transporte.call(Constants.namespace+metodo, sobre);
		   			
		   			//resultado
		   			resultado = (SoapPrimitive) sobre.getResponse();	   					   			
			   		success = true;
			   		
		   			} catch (Exception e) {
	   					Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
		   				e.printStackTrace();
		   				success = false;
		   			}
	      	    waitingForThread = false;
      	    }	      	      
  	    };
  	    networkThread.start();
  	    
  	    while(waitingForThread){	      	    	
  	    }
  	    
  	    if(success)
  	    	return loadDataToDatabase();
  	    else
  	    	return false;
	  }
	  
	  private boolean loadDataToDatabase()
	  {
		  try
		  {						
			String respuesta=resultado.toString();
			String[] restaurantesWeb = respuesta.split(";");
				
			database.execSQL("DROP TABLE IF EXISTS " + SQLiteHelper.TABLE_ITEM);
			database.execSQL(SQLiteHelper.TABLE_CREATE_ITEM);
						
			for(int i=0;i<restaurantesWeb.length;i++){
				String[] restauranteWebActual=restaurantesWeb[i].split("\\*");								
   				h.create(restauranteWebActual[1], restauranteWebActual[2], Integer.parseInt(restauranteWebActual[3]), Integer.parseInt(restauranteWebActual[5]), Integer.parseInt(restauranteWebActual[4]), Boolean.parseBoolean(restauranteWebActual[6]));				
			}
			success = true;
			Log.i("App.log " + getClass().getSimpleName(), "Exito");
		  }
		  catch(Exception e)
		  {
			  Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
			  e.printStackTrace();
			  success = false;
		  }
		  
		  return success;
	  }	  	  
}
